package com.ruoyi.common.httpclient;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
import org.apache.http.impl.nio.client.HttpAsyncClients;
import org.apache.http.impl.nio.conn.PoolingNHttpClientConnectionManager;
import org.apache.http.impl.nio.reactor.DefaultConnectingIOReactor;
import org.apache.http.nio.reactor.ConnectingIOReactor;
import org.apache.http.nio.reactor.IOReactorException;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

public class ConnectionManagerExample {
    public static void main(String[] args) {
        try {
            // 创建一个连接管理器
            ConnectingIOReactor ioReactor = new DefaultConnectingIOReactor();
            PoolingNHttpClientConnectionManager cm = new PoolingNHttpClientConnectionManager(ioReactor);
            // 设置最大连接数
            cm.setMaxTotal(100);
            // 设置每个路由的最大连接数
            cm.setDefaultMaxPerRoute(20);

            // 创建异步 HTTP 客户端
            CloseableHttpAsyncClient httpClient = HttpAsyncClients.custom()
                    .setConnectionManager(cm)
                    .build();

            // 启动客户端
            httpClient.start();

            makeOneRequest(httpClient);
            TimeUnit.SECONDS.sleep(10);
            makeOneRequest(httpClient);

            // 关闭客户端
            httpClient.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void makeOneRequest(CloseableHttpAsyncClient httpClient) throws InterruptedException, ExecutionException, IOException {
        // 这里可以添加具体的 HTTP 请求代码
        // 创建 HTTP GET 请求
        HttpGet request = new HttpGet("http://localhost:8082/api/service/getSystemTime");

        // 发起异步请求
        Future<HttpResponse> future = httpClient.execute(request, null);

        // 等待请求完成并获取响应
        HttpResponse response = future.get();

        // 处理响应
        if (response.getStatusLine().getStatusCode() == 200) {
            String responseBody = EntityUtils.toString(response.getEntity());
            System.out.println("Response: " + responseBody);
        } else {
            System.out.println("Request failed with status code: " + response.getStatusLine().getStatusCode());
        }
    }
}
